<?php  
session_start();

function fetchData($table) {
	$sql = "SELECT * FROM ".$table;
	$query = mysql_query($sql);
	while($row = mysql_fetch_assoc($query)){
		$data[] = $row;
	}
	return $data;
}

function validateData($data) {
	foreach ($data as $key => $value) {
		if ($value == "") {
			$data[$key] = "--------- Missing information ---------";
		}
	}
	return $data;
}

function getRoom($id) {
	$sql = "SELECT * FROM room WHERE id = '".$id."'";
	$query = mysql_query($sql);
	$data = mysql_fetch_array($query);
	return $data;
}

function getAgent($id) {
	$sql = "SELECT * FROM agent WHERE id = '".$id."'";
	$query = mysql_query($sql);
	$data = mysql_fetch_array($query);
	return $data;
}

function fetchAgent() {
	$sql = "SELECT * FROM agent WHERE is_active = '1'";
	$query = mysql_query($sql);
	$result = array();
	while ($baris = mysql_fetch_array($query)) {
		$data["id"] = $baris["id"];
		$data["nama"] = $baris["nama"];
		array_push($result, $data);
	}
	return $result;
}

if(($_SERVER["SCRIPT_NAME"] !== "/login.php") && (!isset($_SESSION["idUser"]))){
	header("Location: login.php");
} else {
	if (isset($_SESSION["idUser"])) {
		$sql_header_tipe_user = "SELECT tipe_user.* FROM user
		INNER JOIN tipe_user  
		ON user.idtipe_user = tipe_user.id
		WHERE user.id = '$_SESSION[idUser]'";

		$query_header_tipe_user = mysql_query($sql_header_tipe_user);
		$result_header_tipe_user = mysql_fetch_array($query_header_tipe_user);

	  	// GLOBAL VARIABLE
		$global_kode_user = $result_header_tipe_user["kode"];
	}
}

// ------------VALIDASI NAMA----------------

function validateEditName($id,$name,$table) {
	$sql = "SELECT * FROM ".$table." a WHERE a.nama = '".$name."' AND a.id <> '".$id."'";
	$query = mysql_query($sql);
	$data = mysql_num_rows($query);
	return $data;
}

function validateAddName($name,$table) {
	$sql = "SELECT * FROM ".$table." a WHERE a.nama = '".$name."'";
	$query = mysql_query($sql);
	$data = mysql_num_rows($query);
	return $data;
}

// ------------VALIDASI KODE----------------

function validateEditCode($id,$kode,$table) {
	$sql = "SELECT * FROM ".$table." a WHERE a.kode = '".$kode."' AND a.id <> '".$id."'";
	$query = mysql_query($sql);
	$data = mysql_num_rows($query);
	return $data;
}

function validateAddCode($kode,$table) {
	$sql = "SELECT * FROM ".$table." a WHERE a.kode = '".$kode."'";
	$query = mysql_query($sql);
	$data = mysql_num_rows($query);
	return $data;
}
?>